package com.ktg.handler;


import com.ktg.ktgcommon.constant.Constants;
import com.ktg.ktgcommon.domain.user.SysUser;
import com.ktg.ktgcommon.result.R;
import com.ktg.ktgcommon.service.RedisService;
import com.ktg.ktgcommon.utils.JSONUtils;
import com.ktg.ktgcommon.utils.JWTUtils;
import com.ktg.ktgcommon.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUser tUser = (SysUser) authentication.getPrincipal();
        String userJSON = JSONUtils.toJSON(tUser);
        String jwt= JWTUtils.createJWT(userJSON);
        redisService.setValue(Constants.REDIS_JWT_KEY+tUser.getUserId(),jwt);
        String rememberMe = request.getParameter("rememberMe");
        if (Boolean.parseBoolean(rememberMe)) {
            redisService.expire(Constants.REDIS_JWT_KEY+tUser.getUserId(),Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        }else {
            redisService.expire(Constants.REDIS_JWT_KEY+tUser.getUserId(),Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
        }
        R result = R.OK(jwt);
        String resultJSON = JSONUtils.toJSON(result);
        ResponseUtils.write(response, resultJSON);
    }
}
